<?php 
class Address extends CI_Controller {
	private $error = array();
	  
  	public function index() {
    	if (!$this->customer->isLogged()) {
	  		$this->session->set_userdata('redirect', site_url('account/address'));

	  		redirect(site_url('account/login')); 
    	}
	
    	$this->lang->load('account/address');

		$this->document->setTitle($this->lang->line('heading_title'));
		
		$this->load->model('account/Model_Address');
		
		$this->getList();
  	}

  	public function insert() {
    	if (!$this->customer->isLogged()) {
	  		$this->session->set_userdata('redirect', site_url('account/address'));

	  		redirect(site_url('account/login')); 
    	} 

    	$this->lang->load('account/address');

		$this->document->setTitle($this->lang->line('heading_title'));
		
		$this->load->model('account/Model_Address');
			
    	if (($this->input->server('REQUEST_METHOD') == 'POST') && $this->validateForm()) {
			$this->Model_Address->addAddress($this->input->post());
			
      		$this->session->set_userdata('success', $this->lang->line('text_insert'));

	  		redirect(site_url('account/address'));
    	} 
	  	
		$this->getForm();
  	}

  	public function update() {
    	if (!$this->customer->isLogged()) {
	  		$this->session->set_userdata('redirect', site_url('account/address'));

	  		redirect(site_url('account/login')); 
    	} 
		
    	$this->lang->load('account/address');

		$this->document->setTitle($this->lang->line('heading_title'));
		
		$this->load->model('account/Model_Address');
		
    	if (($this->input->server('REQUEST_METHOD') == 'POST') && $this->validateForm()) {
       		$this->Model_Address->editAddress($this->uri->segment(4), $this->input->post());
	  		
			if ($this->session->userdata('shipping_address_id') && ((int)$this->uri->segment(4) == $this->session->userdata('shipping_address_id'))) {
	  			$this->session->unset_userdata('shipping_methods');
				$this->session->unset_userdata('shipping_method');	

				if ($this->hkcart->hasShipping()) {
					$this->tax->setZone($this->input->post('country_id'), $this->input->post('zone_id'));
				}
			}

			if ($this->session->userdata('payment_address_id') && ((int)$this->uri->segment(4) == $this->session->userdata('payment_address_id'))) {
	  			$this->session->unset_userdata('payment_methods');
				$this->session->unset_userdata('payment_method');
				
				if (!$this->hkcart->hasShipping()) {
					$this->tax->setZone($this->input->post('country_id'), $this->input->post('zone_id'));
				}		
			}
			
			$this->session->set_userdata('success', $this->lang->line('text_update'));
	  
	  		redirect(site_url('account/address'));
    	} 
	  	
		$this->getForm();
  	}

  	public function delete() {
    	if (!$this->customer->isLogged()) {
	  		$this->session->set_userdata('redirect', site_url('account/address'));

	  		redirect(site_url('account/login')); 
    	} 
			
    	$this->lang->load('account/address');

		$this->document->setTitle($this->lang->line('heading_title'));
		
		$this->load->model('account/Model_Address');
		
    	if (((int)$this->uri->segment(4) != 0) && $this->validateDelete()) {
			$this->Model_Address->deleteAddress((int)$this->uri->segment(4));	

			if ($this->session->userdata('shipping_address_id') && ((int)$this->uri->segment(4) == $this->session->userdata('shipping_address_id'))) {
	  			$this->session->unset_userdata('shipping_address_id');
				$this->session->unset_userdata('shipping_methods');
				$this->session->unset_userdata('shipping_method');	
				
				
				if ($this->hkcart->hasShipping()) {
					$this->tax->setZone($this->cconfig->get('config_country_id'), $this->cconfig->get('config_zone_id'));
				}				
			}

			if ($this->session->userdata('payment_address_id') && ((int)$this->uri->segment(4) == $this->session->userdata('payment_address_id'))) {
	  			$this->session->unset_userdata('payment_address_id');
				$this->session->unset_userdata('payment_methods');
				$this->session->unset_userdata('payment_method');	
				
				if (!$this->hkcart->hasShipping()) {
					$this->tax->setZone($this->cconfig->get('config_country_id'), $this->cconfig->get('config_zone_id'));
				}								
			}
			
			$this->session->set_userdata('success', $this->lang->line('text_delete'));
	  
	  		redirect(site_url('account/address'));
    	}
	
		$this->getList();	
  	}

  	private function getList() {
      	$data['breadcrumbs'][] = array(
        	'text'      => $this->lang->line('text_home'),
			'href'      => site_url('common/home'),
        	'separator' => false
      	); 

      	$data['breadcrumbs'][] = array(
        	'text'      => $this->lang->line('text_account'),
			'href'      => site_url('account/account'),
        	'separator' => $this->lang->line('text_separator')
      	);

      	$data['breadcrumbs'][] = array(
        	'text'      => $this->lang->line('heading_title'),
			'href'      => site_url('account/address'),
        	'separator' => $this->lang->line('text_separator')
      	);
			
    	$data['heading_title'] = $this->lang->line('heading_title');

    	$data['text_address_book'] = $this->lang->line('text_address_book');
		$data['text_first_address'] = $this->lang->line('text_first_address');
		$data['text_other_address'] = $this->lang->line('text_other_address');
   
    	$data['button_new_address'] = $this->lang->line('button_new_address');
    	$data['button_edit'] = $this->lang->line('button_edit');
    	$data['button_delete'] = $this->lang->line('button_delete');
		$data['button_back'] = $this->lang->line('button_back');

		if (isset($this->error['warning'])) {
    		$data['error_warning'] = $this->error['warning'];
		} else {
			$data['error_warning'] = '';
		}
		
		if ($this->session->userdata('success')) {
			$data['success'] = $this->session->userdata('success');
		
    		$this->session->unset_userdata('success');
		} else {
			$data['success'] = '';
		}
		
    	$data['addresses'] = array();
		
		$firstaddress_id = $this->Model_Address->getFirstAddressId();
		
		$results = $this->Model_Address->getAddress($firstaddress_id['address_id']);
		
		$firstformat = '{firstname} {lastname}' . "\n" . '{company}' . "\n" . '{address_1}' . "\n" . '{address_2}' . "\n" . '{city} {postcode}' . "\n" . '{zone}' . "\n" . '{country}';
		
		$firstfind = array(
	  			'{firstname}',
	  			'{lastname}',
	  			'{company}',
      			'{address_1}',
      			'{address_2}',
     			'{city}',
      			'{postcode}',
      			'{zone}',
				'{zone_code}',
      			'{country}'
			);
	
			$firstreplace = array(
	  			'firstname' => $results['firstname'],
	  			'lastname'  => $results['lastname'],
	  			'company'   => $results['company'],
      			'address_1' => $results['address_1'],
      			'address_2' => $results['address_2'],
      			'city'      => $results['city'],
      			'postcode'  => $results['postcode'],
      			'zone'      => $results['zone'],
				'zone_code' => $results['zone_code'],
      			'country'   => $results['country']  
			);

      		$data['firstaddress'] = array(
        		'address_id' => $firstaddress_id['address_id'],
        		'address'    => str_replace(array("\r\n", "\r", "\n"), '<br />', preg_replace(array("/\s\s+/", "/\r\r+/", "/\n\n+/"), '<br />', trim(str_replace($firstfind, $firstreplace, $firstformat)))),
        		'update'     => site_url('account/address/update/' . $firstaddress_id['address_id']),
				'delete'     => site_url('account/address/delete/' . $firstaddress_id['address_id'])
      		);

		$results = $this->Model_Address->getAddresses($firstaddress_id['address_id']);

    	foreach ($results as $result) {
			if ($result['address_format']) {
      			$format = $result['address_format'];
    		} else {
				$format = '{firstname} {lastname}' . "\n" . '{company}' . "\n" . '{address_1}' . "\n" . '{address_2}' . "\n" . '{city} {postcode}' . "\n" . '{zone}' . "\n" . '{country}';
			}
		
    		$find = array(
	  			'{firstname}',
	  			'{lastname}',
	  			'{company}',
      			'{address_1}',
      			'{address_2}',
     			'{city}',
      			'{postcode}',
      			'{zone}',
				'{zone_code}',
      			'{country}'
			);
	
			$replace = array(
	  			'firstname' => $result['firstname'],
	  			'lastname'  => $result['lastname'],
	  			'company'   => $result['company'],
      			'address_1' => $result['address_1'],
      			'address_2' => $result['address_2'],
      			'city'      => $result['city'],
      			'postcode'  => $result['postcode'],
      			'zone'      => $result['zone'],
				'zone_code' => $result['zone_code'],
      			'country'   => $result['country']  
			);

      		$data['addresses'][] = array(
        		'address_id' => $result['address_id'],
        		'address'    => str_replace(array("\r\n", "\r", "\n"), '<br />', preg_replace(array("/\s\s+/", "/\r\r+/", "/\n\n+/"), '<br />', trim(str_replace($find, $replace, $format)))),
        		'update'     => site_url('account/address/update/' . $result['address_id']),
				'delete'     => site_url('account/address/delete/' . $result['address_id'])
      		);
    	}

    	$data['insert'] = site_url('account/address/insert');
		$data['back'] = site_url('account/account');
				
		$data['header'] = helper_load_header();
		$data['column_left'] = helper_load_left();
		$data['column_right'] = helper_load_right();
		$data['content_top'] = helper_load_top();
		$data['content_bottom'] = helper_load_bottom();
		$data['footer'] = helper_load_footer();
		
		
		$this->load->view("account/address_list", $data);	
  	}

  	private function getForm() {
      	$data['breadcrumbs'] = array();

      	$data['breadcrumbs'][] = array(
        	'text'      => $this->lang->line('text_home'),
			'href'      => site_url('common/home'),       	
        	'separator' => false
      	); 

      	$data['breadcrumbs'][] = array(
        	'text'      => $this->lang->line('text_account'),
			'href'      => site_url('account/account'),
        	'separator' => $this->lang->line('text_separator')
      	);

      	$data['breadcrumbs'][] = array(
        	'text'      => $this->lang->line('heading_title'),
			'href'      => site_url('account/address'),        	
        	'separator' => $this->lang->line('text_separator')
      	);
		
		if ((int)$this->uri->segment(4) == 0) {
      		$data['breadcrumbs'][] = array(
        		'text'      => $this->lang->line('text_edit_address'),
				'href'      => site_url('account/address/insert'),       		
        		'separator' => $this->lang->line('text_separator')
      		);
		} else {
      		$data['breadcrumbs'][] = array(
        		'text'      => $this->lang->line('text_edit_address'),
				'href'      => site_url('account/address/update/' . (int)$this->uri->segment(4)),       		
        		'separator' => $this->lang->line('text_separator')
      		);
		}
						
    	$data['heading_title'] = $this->lang->line('heading_title');
    	
		$data['text_edit_address'] = $this->lang->line('text_edit_address');
    	$data['text_address_type_1'] = $this->lang->line('text_address_type_1');
    	$data['text_address_type_2'] = $this->lang->line('text_address_type_2');
    	$data['text_yes'] = $this->lang->line('text_yes');
    	$data['text_no'] = $this->lang->line('text_no');
		$data['text_select'] = $this->lang->line('text_select');
		
    	$data['entry_firstname'] = $this->lang->line('entry_firstname');
    	$data['entry_lastname'] = $this->lang->line('entry_lastname');
    	$data['entry_company'] = $this->lang->line('entry_company');
    	$data['entry_address'] = $this->lang->line('entry_address');
    	$data['entry_address_1'] = $this->lang->line('entry_address_1');
    	$data['entry_address_2'] = $this->lang->line('entry_address_2');
    	$data['entry_address_type'] = $this->lang->line('entry_address_type');
    	$data['entry_postcode'] = $this->lang->line('entry_postcode');
    	$data['entry_city'] = $this->lang->line('entry_city');
    	$data['entry_country'] = $this->lang->line('entry_country');
    	$data['entry_zone'] = $this->lang->line('entry_zone');
    	$data['entry_default'] = $this->lang->line('entry_default');

    	$data['button_continue'] = $this->lang->line('button_continue');
    	$data['button_back'] = $this->lang->line('button_back');

		if (isset($this->error['firstname'])) {
    		$data['error_firstname'] = $this->error['firstname'];
		} else {
			$data['error_firstname'] = '';
		}
		
		if (isset($this->error['lastname'])) {
    		$data['error_lastname'] = $this->error['lastname'];
		} else {
			$data['error_lastname'] = '';
		}
		
		if (isset($this->error['address_1'])) {
    		$data['error_address_1'] = $this->error['address_1'];
		} else {
			$data['error_address_1'] = '';
		}
		
		if (isset($this->error['city'])) {
    		$data['error_city'] = $this->error['city'];
		} else {
			$data['error_city'] = '';
		}
		
		if (isset($this->error['postcode'])) {
    		$data['error_postcode'] = $this->error['postcode'];
		} else {
			$data['error_postcode'] = '';
		}

		if (isset($this->error['country'])) {
			$data['error_country'] = $this->error['country'];
		} else {
			$data['error_country'] = '';
		}

		if (isset($this->error['zone'])) {
			$data['error_zone'] = $this->error['zone'];
		} else {
			$data['error_zone'] = '';
		}
		
		if ((int)$this->uri->segment(4) == 0) {
    		$data['action'] = site_url('account/address/insert');
		} else {
    		$data['action'] = site_url('account/address/update/' . (int)$this->uri->segment(4));
		}
		
    	if (((int)$this->uri->segment(4) != 0) && ($this->input->server('REQUEST_METHOD') != 'POST')) {
			$address_info = $this->Model_Address->getAddress((int)$this->uri->segment(4));
		}
	
    	if ($this->input->post('firstname')) {
      		$data['firstname'] = $this->input->post('firstname');
    	} elseif (isset($address_info)) {
      		$data['firstname'] = $address_info['firstname'];
    	} else {
			$data['firstname'] = '';
		}

    	if ($this->input->post('lastname')) {
      		$data['lastname'] = $this->input->post('lastname');
    	} elseif (isset($address_info)) {
      		$data['lastname'] = $address_info['lastname'];
    	} else {
			$data['lastname'] = '';
		}

    	if ($this->input->post('company')) {
      		$data['company'] = $this->input->post('company');
    	} elseif (isset($address_info)) {
			$data['company'] = $address_info['company'];
		} else {
      		$data['company'] = $this->lang->line('text_input_company');
    	}

    	if ($this->input->post('address_1')) {
      		$data['address_1'] = $this->input->post('address_1');
    	} elseif (isset($address_info)) {
			$data['address_1'] = $address_info['address_1'];
		} else {
      		$data['address_1'] = '';
    	}

    	if ($this->input->post('address_2')) {
      		$data['address_2'] = $this->input->post('address_2');
    	} elseif (isset($address_info)) {
			$data['address_2'] = $address_info['address_2'];
		} else {
      		$data['address_2'] = '';
    	}	

		if ($this->input->post('address_type')) {
    		$data['address_type'] = $this->input->post('address_type');
    	} elseif (isset($address_info)) {
			$data['address_type'] = $address_info['address_type'];
		} else {
			$data['address_type'] = 1;
		}

    	if ($this->input->post('postcode')) {
      		$data['postcode'] = $this->input->post('postcode');
    	} elseif (isset($address_info)) {
			$data['postcode'] = $address_info['postcode'];			
		} else {
      		$data['postcode'] = '';
    	}

    	if ($this->input->post('city')) {
      		$data['city'] = $this->input->post('city');
    	} elseif (isset($address_info)) {
			$data['city'] = $address_info['city'];
		} else {
      		$data['city'] = '';
    	}

    	if ($this->input->post('country_id')) {
      		$data['country_id'] = $this->input->post('country_id');
    	}  elseif (isset($address_info)) {
      		$data['country_id'] = $address_info['country_id'];			
    	} else {
      		$data['country_id'] = $this->cconfig->get('config_country_id');
    	}

    	if ($this->input->post('zone_id')) {
      		$data['zone_id'] = $this->input->post('zone_id');
    	}  elseif (isset($address_info)) {
      		$data['zone_id'] = $address_info['zone_id'];			
    	} else {
      		$data['zone_id'] = '';
    	}
		
		$this->load->model('localisation/Model_Country');
		
    	$data['countries'] = $this->Model_Country->getCountries();

    	if ($this->input->post('default')) {
      		$data['default'] = $this->input->post('default');
    	} elseif ((int)$this->uri->segment(4) != 0) {
      		$data['default'] = $this->customer->getAddressId() == (int)$this->uri->segment(4);
    	} else {
			$data['default'] = false;
		}

    	$data['back'] = site_url('account/address');
		
		$data['header'] = helper_load_header();
		$data['column_left'] = helper_load_left();
		$data['column_right'] = helper_load_right();
		$data['content_top'] = helper_load_top();
		$data['content_bottom'] = helper_load_bottom();
		$data['footer'] = helper_load_footer();
		
		
		$this->load->view("account/address_form", $data);	
  	}
	
  	private function validateForm() {
    	if ((strlen(utf8_decode($this->input->post('firstname'))) < 1) || (strlen(utf8_decode($this->input->post('firstname'))) > 32)) {
      		$this->error['firstname'] = $this->lang->line('error_firstname');
    	}

    	if ((strlen(utf8_decode($this->input->post('lastname'))) < 1) || (strlen(utf8_decode($this->input->post('lastname'))) > 32)) {
      		$this->error['lastname'] = $this->lang->line('error_lastname');
    	}

    	if ((strlen(utf8_decode($this->input->post('address_1'))) < 3) || (strlen(utf8_decode($this->input->post('address_1'))) > 128)) {
      		$this->error['address_1'] = $this->lang->line('error_address_1');
    	}

/*    	if ((strlen(utf8_decode($this->input->post('city'))) < 2) || (strlen(utf8_decode($this->input->post('city'))) > 128)) {
      		$this->error['city'] = $this->lang->line('error_city');
    	}*/
		
		$this->load->model('localisation/Model_Country');
		
		$country_info = $this->Model_Country->getCountry($this->input->post('country_id'));
		
		if ($country_info && $country_info['postcode_required'] && (strlen(utf8_decode($this->input->post('postcode'))) < 2) || (strlen(utf8_decode($this->input->post('postcode'))) > 10)) {
			$this->error['postcode'] = $this->lang->line('error_postcode');
		}
		
    	if ($this->input->post('country_id') == '') {
      		$this->error['country'] = $this->lang->line('error_country');
    	}
		
    	if ($this->input->post('zone_id') == '') {
      		$this->error['zone'] = $this->lang->line('error_zone');
    	}
		
    	if (!$this->error) {
      		return true;
		} else {
      		return false;
    	}
  	}

  	private function validateDelete() {
    	if ($this->Model_Address->getTotalAddresses() == 1) {
      		$this->error['warning'] = $this->lang->line('error_delete');
    	}

    	if ($this->customer->getAddressId() == (int)$this->uri->segment(4)) {
      		$this->error['warning'] = $this->lang->line('error_default');
    	}

    	if (!$this->error) {
      		return true;
    	} else {
      		return false;
    	}
  	}
	
  	public function zone() {	
		$output = '<option value="">' . $this->lang->line('text_select') . '</option>';

		$this->load->model('localisation/Model_Zone');

    	$results = $this->Model_Zone->getZonesByCountryId((int)$this->uri->segment(4));
        
      	foreach ($results as $result) {
        	$output .= '<option value="' . $result['zone_id'] . '"';
	
	    	if (((int)$this->uri->segment(5) != 0) && ((int)$this->uri->segment(5) == $result['zone_id'])) {
	      		$output .= ' selected="selected"';
	    	}
	
	    	$output .= '>' . $result['name'] . '</option>';
    	} 
		
		if (!$results) {
		  	$output .= '<option value="0">' . $this->lang->line('text_none') . '</option>';
    	}
	
		echo $output;
  	}  
}
?>